package luke4fun.wheresmymoney;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.SearchView;

import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.adapter.list.impl.SearchListAdapter;
import luke4fun.wheresmymoney.bean.SearchBean;
import luke4fun.wheresmymoney.service.async.SearchAsyncTask;

public class SearchableActivity extends ListActivity {

	private BasicAdapter<SearchBean> adapter;
	private String query;
	private SearchView searchView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_search);
	    adapter = new SearchListAdapter(this);

	    // Get the intent, verify the action and get the query
	    Intent intent = getIntent();
	    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	    	query = intent.getStringExtra(SearchManager.QUERY);
	    	doSearch(query);
	    }
	    getActionBar().setDisplayShowTitleEnabled(false);
	    getActionBar().setDisplayHomeAsUpEnabled(true);
	    
	    setListAdapter(adapter);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_search, menu);
		
		// Get the SearchView and set the searchable configuration
	    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	    
	    menu.findItem(R.id.menu_search).expandActionView();
	    searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
	    // Assumes current activity is the searchable activity
	    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
	    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
	    searchView.setFocusable(true);
	    searchView.requestFocus();
	    searchView.setQuery(query, false);
	    
		return true;
	}
	
	@Override
	public void onNewIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	    	query = intent.getStringExtra(SearchManager.QUERY);
		    searchView.setQuery(query, false);
	    	doSearch(query);
	    }
	}
	
	private void doSearch(String query) {
		new SearchAsyncTask(this, adapter).execute(query);
	}
}
